#include "UDPWorker.h"
#include <QRegularExpression>

UDPWorker::UDPWorker(QObject *parent)
    : QObject{parent}
{
    udpSocket = new QUdpSocket(this);
    udpSocket->bind(9001); // 绑定到本地端口12345
    desAddress = new QHostAddress("127.0.0.1");
    connect(udpSocket, &QUdpSocket::readyRead, this, &UDPWorker::processPendingDatagrams);


}

void UDPWorker::slot_sendData(QList<bool> bList)
{
    if(bList.size() != 2)
        return;
    QString sendInfo = QString("{%1,%2}").arg(static_cast<int>(bList.at(0))).arg(static_cast<int>(bList.at(1)));
    QByteArray datagram = sendInfo.toUtf8();
    emit sig_DialogShowTxData(sendInfo);
    // 发送数据到指定的地址和端口
    qint64 bytesWritten = udpSocket->writeDatagram(datagram, *desAddress, Port);

    if (bytesWritten == -1)
    {
        qDebug() << "Failed to send datagram:" << udpSocket->errorString();
        udpSocket->writeDatagram(datagram, *desAddress, Port);
    }
    /*
    else
    {
        qDebug() << "Sent datagram:" << datagram << "to" << (*desAddress).toString() << ":" << Port;
    }
    */
}

void UDPWorker::processPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        QString receivedMessage = QString::fromUtf8(datagram);
        //qDebug() << "Received message from" << sender.toString() << ":" << senderPort << ":" << receivedMessage;


        if(receivedMessage == "{quit}")//推出程序
        {
            emit sig_closeExe();
            return;
        }


        QRegularExpression regex1("{w:(\\d+),h:(\\d+)}");
        QRegularExpressionMatch match = regex1.match(receivedMessage);

        if (match.hasMatch()) {
            QString width = match.captured(1);
            QString height = match.captured(2);
            qDebug() << "Width:" << width << "Height:" << height;
            emit sig_setReSize(width.toInt(),height.toInt());
            return;
        }


        QRegularExpression regex2("{(\\d+),(\\d+),(\\d+),(\\d+)}");
        match = regex2.match(receivedMessage);

        if (match.hasMatch()) {
            QString data1 = match.captured(1);
            QString data2 = match.captured(2);
            QString data3 = match.captured(3);
            QString data4 = match.captured(4);
            QList<bool> bList;
            if(data1 == "1")
                bList << true;
            else
                bList << false;

            if(data2 == "1")
                bList << true;
            else
                bList << false;

            if(data3 == "1")
                bList << true;
            else
                bList << false;

            if(data4 == "1")
                bList << true;
            else
                bList << false;


            // qDebug() << "data1:" << data1 << "data2:" << data2 << "data3:" << data3 << "data4:" << data4;
            emit sig_handleData(bList);
        }



        // if (receivedMessage.size() == 9 && receivedMessage[0] =='{' && receivedMessage[receivedMessage.length() - 1] == '}')
        // {
        //     receivedMessage.remove(0, 1);
        //     // 移除最后一个字符
        //     receivedMessage.remove(receivedMessage.length() - 1, 1);
        //     QStringList dataList  = receivedMessage.split(',');
        //     if(dataList.size() == 4)
        //     {
        //         QList<bool> bList;
        //         foreach (QString data, dataList)
        //         {
        //             bList << static_cast<bool>(data.toInt());
        //         }
        //         emit sig_handleData(bList);
        //     }
        // }
    }
}
